package com.example.interfaces;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * ClassName: SendMsgController
 * author: bob.ly
 * Version: 1.0.0
 * DateTime: 2021/07/26-17:21:00
 * Description:
 */
@Slf4j
@RequestMapping("ttl")
@RestController
public class SendMsgController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 同时给路由为XA,XB的队列传一样的消息.
     *
     * @param message
     */
    @GetMapping("/sendMag/{message}")
    public void sendMsg(@PathVariable("message") String message) {
        rabbitTemplate.convertAndSend("X", "XA", "消息来自 ttl 为 10S 的队列: " + message);
        rabbitTemplate.convertAndSend("X", "XB", "消息来自 ttl 为 40S 的队列: " + message);
        log.info("当前时间：{},发送一条信息给两个 TTL 队列:{}", new Date(), message);
    }

    /**
     * 优化: 作用于队列, 但是存在缺点
     * 缺点：
     *
     * @param message
     * @param ttlTime
     */
    @GetMapping("/sendMag/{message}/{ttlTime}")
    public void sendMsg(@PathVariable("message") String message,
                        @PathVariable("ttlTime") String ttlTime) {
        rabbitTemplate.convertAndSend("X", "XC", message, correlationData -> {
            correlationData.getMessageProperties().setExpiration(ttlTime);
            return correlationData;
        });
        log.info("当前时间：{},发送一条信息给队列:{}, 过期时间是:{}", new Date(), message, ttlTime);
    }
}
